import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:xinxuan/http/http_util_service.dart';
import 'package:xinxuan/router/app_routers.dart';
import 'package:xinxuan/vo/good_detail_vo.dart';

class GoodDetailPageController extends GetxController {

  /// 商品详情
  var goodDetailData = GoodDetailData(id: 0, images: [], title: '', description: '', isStar: 0).obs;
  // // /// 选中的规格Str
  // var specStr = ''.obs;
  /// 购买数量
  var buyNum = 1.obs;
  /// 选中的规格
  var skuArr = <int>[].obs;
  var sukItem = SkuItem(specIds: '').obs;

  @override
  void onReady() {
    Map<String, dynamic> argumentsMap = Get.arguments;
    int goodId = argumentsMap['goodId'];
    getGoodDetail(goodId);
    super.onReady();
  }

  /// 获取商品详情
  getGoodDetail(int goodId) async {
    GoodDetailVo goodDetailVo = await HttpUtilService.getGoodDetail(goodId: goodId);
    goodDetailData.value = goodDetailVo.data!;
    skuArr.value = [];
    goodDetailData.value.attributes!.forEach((attributeItem) {
      skuArr.add(0);
    });
    if (goodDetailData.value.attributes!.length > 0) {
      if (goodDetailData.value.attributes![0].specs!.length > 0) {
        changeSku(0, goodDetailData.value.attributes![0].specs![0].id!);
      }
    }
    Future.delayed(Duration(milliseconds: 100), () {
      update();
    });
  }

  /// 修改选中规格
  changeSku(int index, int skuId) {
    skuArr[index] = skuId;
    String specIds = '';
    skuArr.forEach((item) {
      specIds+= '$item,';
    });
    specIds = specIds.substring(0, specIds.length - 1);
    goodDetailData.value.skus!.forEach((item) {
      if (item.specIds == specIds) {
        sukItem.value = item;
      }
    });
  }

  /// 确认订单
  jumpConfirmOrder({required bool isSheet}) {
    if (goodDetailData.value.id! <= 0) {
      return;
    }
    if (sukItem.value.specIds == '') {
      EasyLoading.showToast('请选择规格');
      return;
    }
    if (isSheet) {
      Get.back();
    }
    Get.toNamed(
      '${AppRouters.COMMON_PAGE}${AppRouters.GOOD_DETAIL_PAGE}${AppRouters.STORE_CONFIRM_ORDER_PAGE}',
      arguments: {
        'productId': goodDetailData.value.id!,
        'headImage': goodDetailData.value.images![0],
        'title': goodDetailData.value.title,
        'price': goodDetailData.value.price,
        'quantity': buyNum.value,
        'skuId': sukItem.value.id,
        'specStr': sukItem.value.specStr,
      }
    );
  }

}